/**
 * wait 使用
 */
public class WaitThread {
    public static void main(String[] args) {
        Object lock = new Object();
        Object lock2 = new Object();

        Thread t1 = new Thread(() -> {
            System.out.println("线程1开始执行");
            try {
                synchronized (lock) {
                    System.out.println("线程1调用wait方法....");
                    // 无限期的等待状态
                    lock.wait();
                    System.out.println("线程1：恢复执行之后又进入休眠状态");
                    Thread.sleep(2000);
                    System.out.println("线程1执行完成");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "线程1");


        Thread t2 = new Thread(() -> {
            System.out.println("线程2开始执行");
            try {
                synchronized (lock) {
                    System.out.println("线程2调用wait方法....");
                    // 无限期的等待状态
                    lock.wait();
                    System.out.println("线程2：恢复执行之后又进入休眠状态");
                    Thread.sleep(2000);
                    System.out.println("线程2执行完成");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "线程2");

        Thread t3 = new Thread(() -> {
            System.out.println("线程3开始执行");
            try {
                synchronized (lock) {
                    System.out.println("线程3调用wait方法....");
                    // 无限期的等待状态
                    lock.wait();
                    System.out.println("线程3：恢复执行之后又进入休眠状态");
                    Thread.sleep(2000);
                    System.out.println("线程3执行完成");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "线程3");

        t1.start();
        t2.start();
        t3.start();


        // 唤醒 lock 对象上休眠的线程的（随机唤醒一个）
        Thread t4 = new Thread(() -> {
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
            }
            System.out.println("线程4：开始执行");
            synchronized (lock) {
                // 发出唤醒通知
                lock.notifyAll();
                System.out.println("线程4：执行了唤醒操作");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                }
                System.out.println("线程4：synchronized 执行完了");
            }
        }, "线程4");
        t4.start();

    }
}
